package com.ckzp.jfinal.system.controller;

import com.alibaba.fastjson.JSON;
import com.ckzp.core.ConfigUtil;
import com.ckzp.core.json.Jmode;
import com.ckzp.core.json.JsonUtil;
import com.ckzp.jfinal.base.PageSearch;
import com.ckzp.jfinal.plugins.trans.TransData;
import com.ckzp.jfinal.system.WebSite;
import com.ckzp.jfinal.system.cache.SysRoleCache;
import com.ckzp.jfinal.system.model.*;
import com.ckzp.plugins.layui.LayuiData;
import com.ckzp.core.json.JsonResult;
import com.ckzp.core.model.Datas;
import com.ckzp.core.util.StringUtil;
import com.ckzp.jfinal.base.BaseController;
import com.ckzp.jfinal.form.FormData;
import com.ckzp.jfinal.form.FormSelect;
import com.ckzp.jfinal.interceptor.Admins;
import com.ckzp.jfinal.interceptor.Roles;
import com.ckzp.jfinal.plugins.UpImage;
import com.ckzp.jfinal.system.cache.SysMenuCache;
import com.ckzp.jfinal.system.model.SysMenu;
import com.ckzp.jfinal.system.util.SysMenuUtil;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 51594 on 2020/6/1.
 */
public class SysMenuController extends BaseController {

    @Admins(roles = "system", name = "", log = false)
    public void index() {
        renderText("默认");
    }


    /**
     * 菜单列表页
     */
    @Admins(roles = "system", name = "菜单列表页", log = false)
    public void SysMenuList() {
        FormData fd = SysMenuUtil.n().getMenuTreeData();
        setAttr("form", fd);
        render("SysMenuList.html");
    }


    /**
     * 列表
     */
    @Admins(roles = "system", name = "重载菜单树Api", log = false)
    public void LoadTreeDataApi() {
        FormData fd = SysMenuUtil.n().getMenuTreeData();
        renderJson(fd.toJson());
    }

    /**
     * 查询显示子菜单列表Api
     */
    @Admins(roles = "system", name = "查询显示子菜单列表Api", log = false)
    public void SysMenuListDataApi() {

        PageSearch ps = PageSearch.n()
                .setTable("sys_menu")
                .search("menu_grade", getParaInt("grade", 0) + 1)
                .search("pmenu_id", getParaInt("pmenu_id", 0))
                .like("menu_path", getPara("menupath"))
                .orderby("sindex")
                .initSearch(getRequest());
        Page<SysMenu> pages = ps.paginate(SysMenu.dao);

        List<SysMenu> datalist = pages.getList();
        FormSelect fs = FormSelect.n().setSource("`1`一级菜单`2`二级菜单`3`三级菜单`").setReadOnly(true);
        for (SysMenu menu : datalist) {
            menu.put("menu_grade", fs.showHtml(menu.mod.getStr("menu_grade")));
            menu.put("html_role", StringUtil.delEnd(menu.mod.getStr("menu_role_name"), ","));
            menu.put("html_user", StringUtil.delEnd(menu.mod.getStr("menu_user_name"), ","));
        }
        renderJson(LayuiData.newData().setData(datalist).setCount(pages.getTotalRow()));
    }

    /**
     * 查询显示子菜单列表Api
     */
    @Admins(roles = "system", name = "查询显示子菜单列表Api", log = false)
    public void SysMenuActivityListDataApi() {
        int menu_id = getParaInt("menu_id", 0);
        String sql = "from sys_activity a,sys_menu_activity ma where ma.act_id=a.act_id and ma.menu_id=?";

        PageSearch ps = PageSearch.n().setSql(sql).setSelect("select a.*").addValue(menu_id).init(getRequest());
        ps.like("a.act_path", getPara("menu_path"));
        ps.orderby("a.sindex");
        Page<SysActivity> pages = ps.paginate(SysActivity.dao);
        List<SysActivity> datalist = pages.getList();
        for (SysActivity menu : datalist) {
            menu.put("html_role", StringUtil.delEnd(menu.mod.getStr("act_role_name"), ","));
            menu.put("html_user", StringUtil.delEnd(menu.mod.getStr("act_user_name"), ","));
        }
        renderJson(LayuiData.newData().setData(datalist).setCount(pages.getTotalRow()));
    }

    /**
     * 列表
     */
    @Roles(roles = "system")
    public void DrSysActivityList() {
        int menu_id = getParaInt("menu_id", 0);
        FormData fd = FormData.dao().addData("menu_id", menu_id);
        setAttr("form", fd);
        render("DrSysActivityList.html");
    }

    /**
     * 全部活动列表Api
     */
    @Admins(roles = "system", name = "全部活动列表Api", log = false)
    public void AllSysActivityDataApi() {
        int menu_id = getParaInt("menu_id", 0);
        PageSearch ps = PageSearch.n().setNum(getPage()).setSize(getLimit()).setTable("sys_activity").like("act_path", getPara("actpath")).orderby("act_id desc");
        Page<SysActivity> pages = ps.paginate(SysActivity.dao);
        List<SysActivity> datalist = pages.getList();
        String menuact = SysMenuUtil.n().getMenuActivityString(menu_id);
        System.out.println(menuact);
        for (SysActivity sa : datalist) {
            int act_id = sa.mod.getInt("act_id");
            if (menuact.indexOf("|" + act_id + "|") == -1) {
                sa.put("act_cai", "<button class=\"layui-btn layui-btn-sm btn-edit\" lay-event=\"DrSysActivity\">导入</button>");
            } else {
                sa.put("act_cai", "已采集");
            }
        }
        renderJson(LayuiData.newData().setData(datalist).setCount(pages.getTotalRow()));
    }


    /**
     * 添加菜单页面
     */
    @Admins(roles = "system", name = "添加一级菜单页面", log = false)
    public void AddSysMenuFirst() {
        FormData fd = FormData.dao().setActions("ADD");
        setAttr("menu", new SysMenu());
        setAttr("form", fd);
        render("ModifySysMenuFirst.html");
    }


    /**
     * 添加菜单页面
     */
    @Admins(roles = "system", name = "添加二级菜单页面", log = false)
    public void AddSysMenuSecond() {
        FormData fd = FormData.dao().setActions("ADD");
        fd.addSelect("menu_type_html", FormSelect.n().setName("menu_grade")
                .setSource("`1`一级菜单`2`二级菜单`")
                .setLayFilter("menutype").showHtml(""));

        fd.addSelect("pmenu_id_html", FormSelect.n().setName("pmenu_id")
                .setSource("select menu_id as id,menu_name as name from sys_menu where menu_type=1 order by sindex")
                .showHtml(""));
        setAttr("menu", new SysMenu().set("pmenu_id", getParaInt("pmenu_id", 0)).set("menu_grade", 2));
        setAttr("form", fd);
        render("ModifySysMenuSecond.html");
    }


    /**
     * 添加菜单页面
     */
    @Admins(roles = "system", name = "添加三级菜单页面", log = false)
    public void AddSysMenuThird() {
        FormData fd = FormData.dao().setActions("ADD");
        fd.addSelect("menu_type_html", FormSelect.n().setName("menu_grade")
                .setSource("`1`一级菜单`2`二级菜单`")
                .setLayFilter("menutype").showHtml(""));

        fd.addSelect("pmenu_id_html", FormSelect.n().setName("pmenu_id")
                .setSource("select menu_id as id,menu_name as name from sys_menu where menu_type=1 order by sindex")
                .showHtml(""));
        setAttr("menu", new SysMenu().set("pmenu_id", getParaInt("pmenu_id", 0)).set("menu_grade", 3).set("menu_path", "[path]/"));
        setAttr("form", fd);
        render("ModifySysMenuThird.html");
    }

    /**
     * 修改菜单页面
     */
    @Admins(roles = "system", name = "修改菜单页面", log = false)
    public void EditSysMenuFirst() {
        String menu_id = getPara("menu_id", "");
        SysMenu o = SysMenu.dao.findById(menu_id);
        FormData fd = FormData.dao().setActions("EDIT");
        setAttr("form", fd);
        setAttr("menu", o);
        render("ModifySysMenuFirst.html");
    }

    /**
     * 修改菜单页面
     */
    @Admins(roles = "system", name = "修改菜单页面", log = false)
    public void EditSysMenuSecond() {
        String menu_id = getPara("menu_id", "");
        SysMenu o = SysMenu.dao.findById(menu_id);
        FormData fd = FormData.dao().setActions("EDIT");
        setAttr("form", fd);
        setAttr("menu", o);
        render("ModifySysMenuSecond.html");
    }

    /**
     * 修改菜单页面
     */
    @Admins(roles = "system", name = "修改菜单页面", log = false)
    public void EditSysMenuThird() {
        String menu_id = getPara("menu_id", "");
        SysMenu o = SysMenu.dao.findById(menu_id);
        FormData fd = FormData.dao().setActions("EDIT");
        setAttr("form", fd);
        setAttr("menu", o);
        render("ModifySysMenuThird.html");
    }


    /**
     * 修改菜单Api
     */
    @Admins(roles = "system", name = "修改菜单Api", log = true)
    public void ModifySysMenuApi() {
        Datas data = getDatas();
        int menu_id = data.getInt("menu_id", 0);//主键
        String actions = data.getStr("actions");//action
        if ("EDIT".equals(actions)) {//修改
            int menu_grade = data.getInt("menu_grade");
            int pmenu_id = data.getInt("pmenu_id");
            // if (menu_grade == 3) pmenu_id = data.getInt("p2_id", 0);
            // if (menu_grade == 4) pmenu_id = data.getInt("p3_id", 0);
            boolean results = SysMenu.dao.findById(menu_id)
                    .set("pmenu_id", pmenu_id)
                    .set("menu_name", data.getStr("menu_name"))
                    .set("menu_desc", data.getStr("menu_desc"))
                    .set("menu_path", data.getStr("menu_path"))
                    .set("menu_icon", data.getStr("menu_icon"))
                    .set("sindex", data.getInt("sindex"))
                    .update();
            SysMenuCache.reload();
            renderJson(Json(results, "修改"));
        } else {//添加
            int menu_type = data.getInt("menu_type");
            int pmenu_id = data.getInt("pmenu_id", 0);
            boolean results = new SysMenu()
                    .set("pmenu_id", pmenu_id)
                    .set("menu_name", data.getStr("menu_name"))
                    .set("menu_grade", data.getInt("menu_grade"))
                    .set("menu_path", data.getStr("menu_path", ""))
                    .set("menu_icon", data.getStr("menu_icon"))
                    .set("menu_desc", data.getStr("menu_desc"))
                    .set("sindex", data.getInt("sindex"))
                    .save();
            SysMenuCache.reload();
            renderJson(Json(results, "添加"));
        }
    }


    /**
     * 删除菜单Api
     */
    @Admins(roles = "system", name = "删除菜单Api", log = true)
    public void DelSysMenuApi() {
        ///////////////////////////////////
        int menu_id = getParaToInt("menu_id", 0);
        int counts = Db.queryInt("select count(*) from sys_menu where pmenu_id=?", menu_id);
        if (counts == 0) {
            if (SysMenu.dao.findById(menu_id).delete()) {
                SysMenuCache.reload();
                renderJson(JsonResult.getResult(0, "删除成功"));
            } else {
                renderJson(JsonResult.getResult(9, "删除失败"));
            }
        } else {
            renderJson(JsonResult.getResult(9, "该菜单下有" + counts + "子菜单,不能删除"));
        }
    }


    /**
     * 导入活动至菜单Api
     */
    @Admins(roles = "system", name = "导入活动至菜单Api", log = true)
    public void DrSysActivityApi() {
        ///////////////////////////////////
        int menu_id = getParaToInt("menu_id", 0);
        int act_id = getParaToInt("act_id", 0);
        Object ma = Db.queryFirst("select * from sys_menu_activity where menu_id=? and act_id=?", menu_id, act_id);
        if (ma == null) {
            Db.save("sys_menu_activity", new Record().set("menu_id", menu_id).set("act_id", act_id));
        }
        renderJson(JsonResult.getResult(0, "导入成功"));
    }


    /**
     * 修改菜单Api
     */
    @Admins(roles = "system", name = "修改菜单Api", log = true)
    public void ModifySysMenuFieldApi() {
        String menu_id = getParaStr("key_id", "");
        String field = getPara("field", "");
        String value = getPara("values", "");
        SysMenu.dao.findById(menu_id).set(field, value).update();
        renderJson(JsonResult.getResult(0, "修改成功"));
    }


    /**
     * 配置菜单角色页
     */
    @Admins(roles = "system", name = "配置菜单角色页", log = false)
    public void SetMenuRole() {
        int menu_id = getParaToInt("menu_id", 0);
        SysMenu menu = SysMenu.dao.findById(menu_id);
        if (menu != null) {
            String[] menu_role_list = StringUtil.split(menu.mod.getStr("menu_role"), "|");
            List myrelist = new ArrayList();
            for (String roleid : menu_role_list) {
                myrelist.add(roleid);
            }
            //取得系统所有角色
            List<SysRole> rolelist = SysRole.dao.findAll();
            List relist = new ArrayList();
            for (int k = 0; k < rolelist.size(); k++) {
                SysRole role = rolelist.get(k);
                TransData td = new TransData();
                td.setValue(role.getStr("role_id"));
                td.setTitle(role.getStr("role_name"));
                relist.add(td);
            }
            set("menu", menu);
            set("all_role", toJsonStr(relist));
            set("select_role", toJsonStr(myrelist));
        }
        render("SetMenuRole.html");
    }


    /**
     * 配置菜单角色Api
     */
    @Admins(roles = "system", name = "配置菜单角色Api", log = false)
    public void SetMenuRoleApi() {
        int menu_id = getParaToInt("menu_id", 0);
        SysMenu menu = SysMenu.dao.findById(menu_id);
        if (menu != null) {
            String json_rolestr = getPara("role_str");
            List list = JsonUtil.json2List(json_rolestr, TransData.class);
            StringBuffer role_str = new StringBuffer();
            StringBuffer role_name_str = new StringBuffer();
            for (int k = 0; k < list.size(); k++) {
                TransData td = (TransData) list.get(k);
                String role = td.getValue();
                role_str.append(role + "|");
                role_name_str.append(td.getTitle() + ",");
            }
            String menu_role = StringUtil.delEnd(role_str.toString(), ",");
            String menu_role_name = StringUtil.delEnd(role_name_str.toString(), ",");
            menu.set("menu_role", menu_role).set("menu_role_name", menu_role_name).update();
            SysMenuUtil.n().reloadMenuRoleByChild(menu.mod.getInt("pmenu_id"));
            SysMenuCache.reload();
            renderJson(JsonResult.getResult(0, "角色设置成功"));
        } else {
            renderJson(JsonResult.getResult(9, "菜单不存在"));
        }
    }


    /**
     * 配置菜单用户页
     */
    @Admins(roles = "system", name = "配置菜单用户页", log = false)
    public void SetMenuUser() {
        int menu_id = getParaToInt("menu_id", 0);
        SysMenu menu = SysMenu.dao.findById(menu_id);
        if (menu != null) {
            String[] menu_user_list = StringUtil.split(menu.mod.getStr("menu_user"), "|");
            List myrelist = new ArrayList();
            for (String userid : menu_user_list) {
                myrelist.add(userid);
            }
            //取得系统所有角色
            List<SysUser> userlist = SysUser.dao.findAll();
            List relist = new ArrayList();
            for (int k = 0; k < userlist.size(); k++) {
                SysUser user = userlist.get(k);
                TransData td = new TransData();
                td.setValue(user.getStr("emp_id"));
                td.setTitle(user.getStr("user_name"));
                relist.add(td);
            }
            set("menu", menu);
            set("all_user", toJsonStr(relist));
            set("select_user", toJsonStr(myrelist));
        }
        render("SetMenuUser.html");
    }


    /**
     * 配置菜单用户Api
     */
    @Admins(roles = "system", name = "配置菜单用户Api", log = false)
    public void SetMenuUserApi() {
        int menu_id = getParaToInt("menu_id", 0);
        SysMenu menu = SysMenu.dao.findById(menu_id);
        if (menu != null) {
            String json_userstr = getPara("user_str");
            List list = JsonUtil.json2List(json_userstr, TransData.class);
            StringBuffer user_str = new StringBuffer();
            StringBuffer user_name_str = new StringBuffer();
            for (int k = 0; k < list.size(); k++) {
                TransData td = (TransData) list.get(k);
                String role = td.getValue();
                user_str.append(role + "|");
                user_name_str.append(td.getTitle() + ",");
            }
            String menu_user = StringUtil.delEnd(user_str.toString(), ",");
            String menu_user_name = StringUtil.delEnd(user_name_str.toString(), ",");
            menu.set("menu_user", menu_user).set("menu_user_name", menu_user_name).update();
            //重载cache
            SysMenuUtil.n().reloadMenuRoleByChild(menu.mod.getInt("pmenu_id"));
            SysMenuCache.reload();
            renderJson(JsonResult.getResult(0, "人员设置成功"));
        } else {
            renderJson(JsonResult.getResult(9, "活动不存在"));
        }
    }


    /**
     * 改变事务活动字段状态Api(0 or 1)
     */
    @Admins(roles = "system", name = "改变事务活动字段状态Api", log = true)
    public void ChangeSysActivityColumnApi() {
        String keyid = getParaStr("key", "");
        String field = getParaStr("field", "");
        String msg = getParaStr("msg", "");
        renderJson(DoBasePub(SysActivity.dao, keyid, field, msg));
    }


    /**
     * 删除菜单活动Api
     */
    @Admins(roles = "system", name = "删除菜单活动Api", log = true)
    public void DelSysMenuActivityApi() {
        int menu_id = getParaInt("menu_id", 0);
        int act_id = getParaInt("act_id", 0);
        Db.delete("delete from sys_menu_activity where menu_id=? and act_id=?", menu_id, act_id);
        renderJson(JsonResult.getResult(0, "删除成功"));
    }

    /**
     * 删除菜单活动Api
     */
    @Admins(roles = "system", name = "删除菜单活动Api", log = true)
    public void ScyActivityPathApi() {
        int menu_id = getParaInt("menu_id", 0);
        int act_id = getParaInt("act_id", 0);
        SysActivity sa = SysActivity.dao.findById(act_id);
        if (sa != null) {
            String actpath = sa.mod.getStr("act_path");
            actpath = StringUtil.replace(actpath, ConfigUtil.getWebAdminPath() + "/", "");
            SysMenu sm = SysMenu.dao.findById(menu_id);
            if (sm != null) {
                sm.set("menu_path", actpath).update();
                SysMenuCache.reload();
            }
        }
        renderJson(JsonResult.getResult(0, "同步成功"));
    }

    /**
     * 图片上传接口
     */
    @Admins(roles = "login", name = "上传图片", log = false)
    public void UploadImages() {
        renderJson(UpImage.n().upload(getRequest(), "show", true, true));
    }

}